<?php
// DO NOT USE DIE() IN THIS SCRIPT!!!!
$permanentData = R::load( 'permanentdata', 1);
$date = $permanentData->date;
$date1 = strtotime(getDateWithDelay(0));
$date2 = strtotime($date);


// We send every day
if((($date1-$date2)/60.0/60.0/24.0) >= 1.0 || isset($_GET['checkAndSendNow'])){
    $allCards = R::findAll( 'card' , ' ORDER BY due_date ASC ');
    $dateTimeNow = strtotime(getDateWithDelay(0));
    $expiringCards = array();
    foreach ($allCards as $card) {
        $asignee = R::load( 'user', $card->asignee);
        if(!is_null($asignee->reminderdays) && isLessThanXDaysRemaining($card->due_date, $asignee->reminderdays)){
            $expiringCards[$card->asignee][] = $card;
        }
    }
    
    if(count($expiringCards) > 0){
        foreach ($expiringCards as $asignee => $expCard){
            sendEmail($asignee,$expiringCards[$asignee]);
        }
    }
    
    // Write to database date of last card check
    $permanentData->date = getDateWithDelay(0);
    R::store($permanentData);
    // Going back
    if(isset($_GET['checkAndSendNow'])){
        header('Location: ' . $_SERVER['HTTP_REFERER']);
    }
}

function isLessThanXDaysRemaining($cardDate, $xDays){
    
    if(is_null($xDays) || $xDays == 0 || is_null($cardDate) || !isset($cardDate)){
        return false;
    }
    $dateTimeNow = strtotime(getDateWithDelay(0));
    $cardDateTime = strtotime($cardDate);
    
    if($dateTimeNow <= $cardDateTime && (($cardDateTime-$dateTimeNow)/60.0/60.0/24.0) <= $xDays){
        return true;
    }
}

function sendEmail($asigneeId, $cards)
{
    date_default_timezone_set("CET");
    $date = getDateWithDelay(0);

    $user = R::load('user', $asigneeId);
    if($user->id == 0){
        return;
    }
    //$email = "gasper.urh@gmail.com";
    $recipient = $user->email;
    $subject = '[Kanbaneros] Some of your cards will expire soon!';
    $body = "<html>
            <body>
            <h2>Following cards will expire soon:</h2>
            ";
    foreach ($cards as $card){
        $body .= "<table style='border: 1px solid black; width: 600px'>"
                . "<tr style='vertical-align: top; text-align: left;'><td style='width: 150px;'>Card name: </td><td><b>$card->title</b></td></tr>"
                . "<tr style='vertical-align: top; text-align: left'><td>Description: </td><td>".nl2br($card->description)."</td></tr>"
                . "<tr style='vertical-align: top; text-align: left'><td>Date of expiry: </td><td>$card->due_date</td></tr>"
                . "</table> <br />";
    }
    $body .= "
        <p>Mail was sent at $date.</p></body>
    </html>";
    
    //echo "<p>Sending mail to: $user->email : </p> $body";
    $headers = "From: webmaster@kanbaneros.com\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    $mailSent = mail($recipient,$subject,$body,$headers);

}